<template>
  <div>
    <Breadcrumb :title="`${title}图片资源管理` " :opt-data="assetOptData"></Breadcrumb>
    <PageLayout>
      <div v-loading="pageLoading" class="table-container height-100 over-flower-auto">
        <div v-if="assetData.length">
          <p v-if="!assetDrag" class="font-color-danger font-size-12 mar-top-0">*拖拽图片后，点击完成排序按钮</p>
          <div  v-if="type==='common'" >
            <div v-for="(commonAsset, cIndex) in imageData" :key="cIndex" >
              <p v-if="commonAsset.images.length || !assetDrag">
              <el-divider content-position="left">{{commonAsset.label}}类</el-divider>
              </p>
              <div class="image-container">
                <!-- 可拖拽区域 -->
                <draggable class="width-100"
                  v-model="commonAsset.images"  group="commonAssets"  @end="onImageEnd" :disabled="assetDrag">
                  <transition-group :class="{dropzone:commonAsset.images.length || !assetDrag}">
                  <div v-for="asset in commonAsset.images" :key="asset._id" class="image-item" >
                   <el-image
                  class="img"
                  :src="`${assetBaseUrl}/file/download/${asset.path}`"
                  fit="cover"></el-image>
                    <i v-if="assetDrag" class="el-icon-delete image-delete-icon" @click="clickDeleteImage(asset._id,'common')"></i>
                   </div>
                  </transition-group>
                </draggable>
              </div>
            </div>
          </div>
          <div v-else>
            <draggable v-model="assetData" @end="onEnd" :disabled="assetDrag">
              <transition-group class="image-container">
                <div v-for="(asset, index) in assetData" :key="index" class="image-item">
                  <el-image
                    class="img"
                    :src="asset.path"
                    :preview-src-list="previewList"
                    :z-index="index"
                    fit="cover"></el-image>
                  <i v-if="assetDrag" class="el-icon-delete image-delete-icon" @click="clickDeleteImage(index,'other')"></i>
                </div>
              </transition-group>
            </draggable>
          </div>

        </div>
        <EmptyContent v-else slot="empty" :opt-data="assetOptData"></EmptyContent>
        <div class="bottom-box" v-if="!assetDrag">
          <el-button size="medium" @click="assetDrag=!assetDrag">取消排序</el-button>
          <el-button size="medium" type="primary" @click="comImgSubmitted" v-if="type==='common'">完成图片排序</el-button>
          <el-button size="medium" type="primary" @click="sortSubmitted" v-else>完成排序</el-button>
        </div>
      </div>
    </PageLayout>
    <el-drawer
      :visible.sync="showAssetDrawer"
      :size="355"
      :before-close="() => showAssetDrawer = false">
      <div slot="title" class="header4">{{`上传${title}图片`}}</div>
      <div class="pad-all-10">
        <el-upload
          ref="upload"
          action="action"
          multiple :limit="30"
          :auto-upload="false"
          :show-file-list="false"
          list-type="picture"
          accept=".jpg,.jpeg,.png,.svg,.gif"
          :on-exceed="handleImageExceed"
          :on-change="handleImageChange">
          <el-button slot="trigger" size="small" type="primary" class="mar-rgt-10">选取图片</el-button>
          <div class="mar-top-10" v-if="type==='common'">
          <el-select  v-model="imageType" placeholder="请选择图片类型" style="{width: 150px}" size="small" class="mar-rgt-10">
            <el-option v-for="item in imageCategory" key="item.value"  :label="item.label" :value="item.value"></el-option>
          </el-select>
            <el-button
              v-show="imageType && this.fileList.length"
              size="small" type="success"
              @click="handleImageUpload">立即上传
            </el-button>
          </div>
          <el-button
            v-else-if="type!=='common'&& this.fileList.length"
            size="small" type="success"
            @click="handleImageUpload">立即上传
          </el-button>
          <div slot="tip" class="el-upload__tip">只能上传 jpg/jpeg/png/svg/gif 文件，且不超过 10MB</div>
        </el-upload>
        <div class="image-container">
          <div v-for="(file, index) in fileList" :key="index" class="image-item">
            <el-image
              class="img"
              :src="file.url"
              :preview-src-list="fileList.map(f => f.url)"
              :z-index="index"
              fit="cover"></el-image>
            <i class="el-icon-delete image-delete-icon" @click="fileList.splice(index, 1)"></i>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import {msgCode} from "@/config/string";
  import {confirmHandle, deepCopy, messageHandle} from "@/utils";
  import {assetBaseUrl} from "@/config/env";
  import {routerMeta} from "@/router/routerMeta";
  import {uploadAssetType, uploadFileType,imageCategory} from "@/config/common";
  import draggable from 'vuedraggable';
  import API from "@/api";

  export default {
    name: "AssetManagement",
    components: {draggable},
    data() {
      return {
        emptyImg: require('@/assets/img/empty-state.png'),
        type: uploadAssetType.common,
        projectId: '',
        roomId: '',
        pageLoading: true,
        srcAssetData: [],
        assetData: [],
        fileList: [],
        showAssetDrawer: false,
        assetDrag: true,
        imageCategory:imageCategory,
        imageType:'',
        assetBaseUrl:assetBaseUrl,
        imageData:[]
      }
    },
    activated() {
      switch (this.$route.name) {
        case routerMeta.commonAsset.name:
          this.type = uploadAssetType.common;
          break;
        case routerMeta.projectAsset.name:
          this.type = uploadAssetType.project;
          break;
        case routerMeta.roomAsset.name:
          this.type = uploadAssetType.room;
          break;
        default:
          break;
      }
      this.projectId = this.$route.params.pid;
      this.roomId = this.$route.params.rid;
      this.srcAssetData = [];
      this.assetData = [];
      this.fileList = [];
      this.getAssetData();
    },
    computed: {
      title() {
        switch (this.type) {
          case uploadAssetType.common:
            return '公共';
          case uploadAssetType.project:
            return '项目';
          case uploadAssetType.room:
            return '房间';
          default:
            return '';
        }
      },
      assetOptData() {
        return [
          {
            type: 'btn',
            label: `上传${this.title}图片`,
            icon: 'icon-tianjia',
            callback: () => {
              this.showAssetDrawer = true;
            }
          },
          {
            type: 'btn',
            label: `图片排序`,
            icon: 'icon-kuozhanziduan',
            callback: () => {
              this.assetDrag = false;
            }
          }
        ];
      },
      previewList() {
        return this.assetData.map(asset => {
          return asset.path
        });
      },

    },
    methods: {
      getAssetData() {
        this.pageLoading = true;
        let Api = () => {
        };
        let params = {};
        switch (this.type) {
          case uploadAssetType.common:
            Api = API.file.commonAssetList;
            break;
          case uploadAssetType.project:
            Api = API.project.projectAssetList;
            params = {projectId: this.projectId};
            break;
          case uploadAssetType.room:
            Api = API.room.roomAssetList;
            params = {roomId: this.roomId};
            break;
          default:
            break;
        }
        Api(params).then(resp => {
          this.pageLoading = false;
          const {data = []} = resp;
          this.srcAssetData = data;
          this.assetData = data.map(asset => {
            const {path = '', filePath = '', sortNo = '', _id = '', fileId = ''} = asset;
            if (this.type === uploadAssetType.common) {
              return {
                path: `${assetBaseUrl}/file/download/${path || filePath}`,
                sortNo: sortNo,
                _id: _id
              }
            } else {
              return {
                path: `${assetBaseUrl}/file/download/${path || filePath}`,
                fileId: fileId
              }
            }

          });
          //给公共图片分类
          const categorizedCommonAssets = imageCategory.reduce((acc, category) => {
            acc[category.value] = data.filter(asset => asset.imageType === category.value);
            return acc;
          }, {});
          categorizedCommonAssets.other.push(...this.srcAssetData.filter(asset => !asset.imageType));
          this.imageData=[
            { label: '图标', name: 'first', type:'icons', images:categorizedCommonAssets.icons},
            { label: 'logo', name: 'second', type:'logo',images:categorizedCommonAssets.logo},
            { label: '背景', name: 'third', type:'bg',images:categorizedCommonAssets.bg},
            { label: 'gif', name: 'fourth',type:'gifs', images:categorizedCommonAssets.gifs},
            { label: '其他', name: 'fifty',type:'other', images:categorizedCommonAssets.other},
          ];
        }).catch(err => {
          this.pageLoading = false;
          console.log('err', err);
        });
      },
      handleImageExceed() {
        this.$message.warning('当前限制选择 30 张图片，已超出 30 张图片！');
      },
      handleImageChange(file) {
        if (file.size / 1024.0 / 1024.0 > 10) {
          this.$message.warning('图片大小不能超过10MB，请重新上传！');
          return false;
        }
        this.fileList.push(file);
      },
      handleImageUpload() {
        const formData = new FormData();
        this.fileList.forEach(file => formData.append("file", file.raw));
        const params = {
          type: uploadFileType.asset,
          assetType: this.type,
          imageType: this.imageType,
        };
        API.file.fileUpload(formData, params).then(resp => {
          const {files = []} = resp.data;
          let Api = () => {
          };
          let params = {};
          switch (this.type) {
            case uploadAssetType.common:
              messageHandle({code: msgCode.UPLOAD_SUCCESS, title: '资源图片'});
              this.showAssetDrawer = false;
              this.fileList = [];
              this.getAssetData();
              break;
            case uploadAssetType.project:
              Api = API.project.projectFileUpdate;
              params = {action: 'add', projectId: this.projectId, files: files};
              break;
            case uploadAssetType.room:
              Api = API.room.roomFileUpdate;
              params = {type: uploadFileType.asset, action: 'add', roomId: this.roomId, files: files};
              break;
            default:
              break;
          }
          Api(params).then(resp => {
            messageHandle({code: msgCode.UPLOAD_SUCCESS, title: '资源图片'});
            this.showAssetDrawer = false;
            this.fileList = [];
            this.getAssetData();
          });
        }).catch(err => {
          console.log('##### err #####', err);
        });
      },
      clickDeleteImage(index,type) {
        confirmHandle({label: `确定删除图片吗?`}).then(() => {
          let asset = {}
          if(type==='other'){
          asset = this.srcAssetData[index];
          }

          let Api = () => {
          };
          let params = {};
          switch (this.type) {
            case uploadAssetType.common:
              Api = API.file.fileDelete;
              params = {_id: index};
              break;
            case uploadAssetType.project:
              Api = API.project.projectFileUpdate;
              params = {action: 'delete', projectId: this.projectId, files: [asset]};
              break;
            case uploadAssetType.room:
              Api = API.room.roomFileUpdate;
              params = {type: uploadFileType.asset, action: 'delete', roomId: this.roomId, files: [asset]};
              break;
            default:
              break;
          }
          Api(params).then(resp => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '资源图片'});
            this.getAssetData();
          });
        }).catch(() => {
        });
      },
      onEnd() {
        this.assetData.forEach((item, index) => {
          item.sortNo = index + 1
        })
        this.$emit('dragEvent', this.assetData);
      },
      sortSubmitted() {
        let changedAsset = [];
        if (this.type === uploadAssetType.common) {
          this.assetData.forEach(obj1 => {
            let obj2 = this.srcAssetData.find(item => item._id === obj1._id);
            if (obj2 && (obj1.sortNo !== obj2.sortNo || obj1._id !== obj2._id)) {
              changedAsset.push({sortNo: obj1.sortNo, _id: obj1._id});
            }
          });
        } else {
          const aIdIndexMap = this.assetData.reduce((map, obj, index) => {
            map[obj.fileId] = index;
            return map;
          }, {});
          this.srcAssetData.sort((obj1, obj2) => aIdIndexMap[obj1.fileId] - aIdIndexMap[obj2.fileId]);
        }
        let Api = () => {
        };
        let params = {};
        switch (this.type) {
          case uploadAssetType.common:
            Api = API.file.fileUpdate;
            params = {files: changedAsset};
            break;
          case uploadAssetType.project:
            Api = API.project.projectFileUpdate;
            params = {action: 'sort', projectId: this.projectId, files: this.srcAssetData};
            break;
          case uploadAssetType.room:
            Api = API.room.roomFileUpdate;
            params = {type: uploadFileType.asset, action: 'sort', roomId: this.roomId, files: this.srcAssetData};
            break;
          default:
            break;
        }
        Api(params).then(resp => {
          messageHandle({code: msgCode.OPERATE_SUCCESS, title: '资源图片排序'});
          this.getAssetData();
        });
        this.assetDrag = !this.assetDrag
        this.getAssetData();

      },

      // 处理拖动事件
      onImageEnd(evt) {
        this.$emit('dragEvent', this.imageData);
      },
      comImgSubmitted() {
        this.imageData.forEach(category => {
          category.images.forEach(obj1 => {
            obj1.imageType = category.type; // 添加 imageType 属性
          });
        });
        API.file.fileUpdate({files:this.srcAssetData}).then(resp => {
          messageHandle({code: msgCode.OPERATE_SUCCESS, title: '资源图片排序'});
          this.getAssetData();
        });
        this.assetDrag = !this.assetDrag

      }
    },
  }
</script>

<style scoped lang="less">

  .dropzone:hover {
    background: #f0f0f0;
  }
  .dropzone.highlight {
    border-color: #4CAF50;
    background: #e8f5e9;
  }
  .dropzone{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    min-height: 100px;;
  }
  .image-container {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    width: 100%;
  }
  .img-title{
    color: #2D69E0;
  }
    .image-item {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100px;
      height: 100px;
      position: relative;
      overflow: hidden;
      border: 1px solid @colorGray90;

      .image-delete-icon {
        position: absolute;
        display: none;
        top: 2px;
        right: 2px;
        color: @colorGray60;
        font-size: 18px;
        cursor: pointer;

        &:hover {
          font-weight: bold;
          color: @colorDanger;
        }
      }

      &:hover {
        .image-delete-icon {
          display: block;
        }
      }
    }
  .bottom-box {
    height: 80px;
    background: #fff;
    position: fixed;
    bottom: 20px;
    right: 30px;

  }
</style>
